import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.*;

@WebServlet("/nanny-data")
public class NannyDataRetrievalServlet extends HttpServlet {

    // 数据库连接信息 - 确保使用UTF-8编码
    private static final String DB_URL = "jdbc:mysql://localhost:3306/baomu?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456"; // 替换为您的MySQL密码

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL JDBC驱动已成功加载");
        } catch (ClassNotFoundException e) {
            System.err.println("无法加载MySQL JDBC驱动");
            e.printStackTrace();
            throw new RuntimeException("无法加载数据库驱动", e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置字符编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 检查用户是否登录
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");

        if (userId == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录");
            return;
        }

        // 从数据库获取保姆资料
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "SELECT * FROM baomu WHERE u_id = ?";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setInt(1, userId);

                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        // 创建JSON格式的响应
                        StringBuilder json = new StringBuilder();
                        json.append("{");
                        json.append("\"b_id\":").append(rs.getInt("b_id")).append(",");
                        json.append("\"u_id\":").append(rs.getInt("u_id")).append(",");
                        json.append("\"b_name\":\"").append(escapeJson(rs.getString("b_name"))).append("\",");
                        json.append("\"b_experience\":\"").append(escapeJson(rs.getString("b_experience"))).append("\",");
                        json.append("\"b_type\":\"").append(escapeJson(rs.getString("b_type"))).append("\",");
                        json.append("\"b_health\":\"").append(escapeJson(rs.getString("b_health"))).append("\",");
                        json.append("\"b_price\":").append(rs.getFloat("b_price")).append(",");
                        json.append("\"b_description\":\"").append(escapeJson(rs.getString("b_description"))).append("\",");
                        json.append("\"b_photo\":\"").append(escapeJson(rs.getString("b_photo"))).append("\"");
                        json.append("}");

                        response.getWriter().write(json.toString());
                    } else {
                        response.getWriter().write("{\"error\": \"未找到保姆资料\"}");
                    }
                }
            }
        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库访问错误");
        }
    }

    // JSON转义方法
    private String escapeJson(String text) {
        if (text == null) return "";
        return text.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}